package wendyeq.iweb.blog.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import wendyeq.iweb.blog.pojo.Tags;
import wendyeq.iweb.blog.service.ITagsService;

@Controller("tagsController")
@RequestMapping("/admin/tags")
public class TagsController {
	private static final Logger logger = Logger.getLogger(TagsController.class);
	
	@Resource(name="tagsServiceImpl")
	private ITagsService tagsService;
	
	@RequestMapping("")
	public String tags(HttpServletRequest request) {
		return "admin/tags";
	}
	
	@RequestMapping("post")
	public String postTags(@RequestParam String tag ,HttpServletRequest request, ModelMap model) {
		this.tagsService.save(new Tags(tag));
		return "admin/tags";
	}
	
	@RequestMapping("update")
	public String updateTags(@RequestParam String oldName ,@RequestParam String newName, HttpServletRequest request, ModelMap model) {
		this.tagsService.modify(oldName, newName);
		return "admin/tags";
	}
	
	@RequestMapping("del/{id}")
	public String delTags(@PathVariable String id, HttpServletRequest request, ModelMap model) {
		this.tagsService.delete(id);
		model.addAttribute("tags", this.tagsService.findAll());
		return "admin/tags";
	}

	@RequestMapping("list/{page}")
	public String getAllTags(@PathVariable int page, HttpServletRequest request , ModelMap model){
		List<Tags> tags = this.tagsService.findAll();
		int tagSize = tags.size();
		if(tagSize<15){
			model.addAttribute("tags",tags );
		}else if(tags.size()-page*15>=0){
			model.addAttribute("tags",tags.subList((page-1)*15,page*15));
		}else {
			model.addAttribute("tags",tags.subList((page-1)*15,tagSize));
		}
		model.addAttribute("tagSize", tagSize);
		model.addAttribute("page", page);
		return "admin/tagsList";
	}
}
